# -*-encoding: utf-8 -*-

from pyramid.view import view_config
from pyramid.view import view_defaults
from pyramid.response import Response
from pyramid.httpexceptions import HTTPFound
import json
from ..utils.Hash.HashUtil import HashUtil
from ..utils.Image.ImageUtil import ImageUtil
from ..utils.DB import MySqlCRUD
import time, os, uuid, shutil, hashlib
import base64
from ..utils.Queue import UploadTasks
from ..utils.SMS import MobSMS
from ..utils.User.User import User
from ..utils.Cache.TokenCache import TokenCache
from ..utils.Cache.ChecksumCache import ChecksumCache
import logging

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
log = logging.getLogger(__name__)

from AppBase import Base
class Achievement(Base):

    @view_config(route_name='AppAchievementUploadRoute', request_method='POST')
    def AppAchievementUploadRoute(self):
        try:
            postParams =  self.request.POST
            tel = postParams.getone('tel')
            tString = postParams.getone('tString')
            eString = postParams.getone('eString')
            tokenString = postParams.getone('tokenString')
            csc = postParams.getone('csc')
            uploadFile = postParams.getone('image_file')
            input_file = uploadFile.file
            suffix = postParams.getone('suffix')
            type = postParams.getone('type')
        except Exception, e:
            log.error(e)
        tmpTokenString = self.calculateToken(tString, tel)
        cache = ChecksumCache()
        if (eString <> HashUtil.getStringMD5(tel + tString)) or (tokenString <> tmpTokenString):
            map = {'RetCode': '145', 'message': '流程验证失败!', 'data': '请重新登录'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)
        tmpCS = cache.getCache(tel)
        if tmpCS <> csc:
            map = {'RetCode': '145', 'message': '流程验证失败!', 'data': '重新提交请求'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)
        # The file instance
        fileMD5 = HashUtil.getFileMD5(input_file.read())
        fileName = fileMD5 + '.' + suffix
        log.debug('[ACHIEVEMENT][MD5]' + fileMD5)

        # The file path
        file_path = os.path.join('/media/img', suffix, fileMD5[0: 2], fileMD5[2: 4], fileName)
        temp_file_path = file_path + '.tmp'
        input_file.seek(0)
        folderName = file_path[0: file_path.rfind('/') + 1]
        if not os.path.exists(folderName):
            os.makedirs(folderName)

        with open(temp_file_path, 'wb') as output_file:
            shutil.copyfileobj(input_file, output_file)
        os.rename(temp_file_path, file_path)

        log.debug(file_path)
        thumb_path = os.path.join('/media/thumb', fileMD5[0: 2], fileMD5[2: 4], fileName)
        thumb_path = thumb_path.replace(suffix, 'jpg')
        log.debug(thumb_path)
        ImageUtil.make_thumb(file_path, thumb_path, 200, 100)

        map = {'RetCode': '', 'message': '', 'data': ''}
        try:
            #'1'表示速搭,'2'表示自由组合
            UploadTasks.uploadAchievementByQueue(fileMD5, file_path, tel, type)
            map = {'RetCode': '0', 'message': '更新我的相册成功!', 'data': file_path}
        except Exception, e:
            log.error(e)
            map = {'RetCode': '143', 'message': '更新我的相册失败!', 'data': file_path}
        jsonStr = json.dumps(map, ensure_ascii=False)
        jsonStr = jsonStr.replace('/media', '/static')
        log.debug(jsonStr)
        return Response(jsonStr)

    @view_config(route_name='AppAchievementFetchRoute', request_method='POST')
    def AppAchievementFetchRoute(self):
        try:
            postParams =  self.request.POST
            tel = postParams.getone('tel')
            tString = postParams.getone('tString')
            eString = postParams.getone('eString')
            tokenString = postParams.getone('tokenString')
            csc = postParams.getone('csc')
        except Exception, e:
            log.error(e)
        tmpTokenString = self.calculateToken(tString, tel)
        cache = ChecksumCache()
        if (eString <> HashUtil.getStringMD5(tel + tString)) or (tokenString <> tmpTokenString):
            map = {'RetCode': '145', 'message': '流程验证失败!', 'data': '请重新登录'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)
        tmpCS = cache.getCache(tel)
        if tmpCS <> csc:
            map = {'RetCode': '145', 'message': '流程验证失败!', 'data': '重新提交请求'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)
        selectSQL = '''
            SELECT MD5, path, achievement_info.type FROM achievement_info
                INNER JOIN user_info
                ON achievement_info.user_id = user_info.ID
                WHERE user_info.tel = %s
                ORDER BY achievement_info.update_time DESC;
        '''
        resultSelect = MySqlCRUD.selectImpl(selectSQL, tel)
        for item in resultSelect:
            itemMD5 = item['MD5']
            thumb_path = os.path.join('/media/thumb', itemMD5[0: 2], itemMD5[2: 4], itemMD5 + '.jpg')
            item['thumb_path'] = thumb_path
        map = {'RetCode': '0', 'message': '获取我的相册成功', 'data': resultSelect, 'total': len(resultSelect)}
        jsonStr = json.dumps(map, ensure_ascii=False)
        jsonStr = jsonStr.replace('/media', '/static')
        #print jsonStr
        return Response(jsonStr)

